package base

import (
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
)

// NacosConfigurator 实现 go-zero 的 Configurator 接口
type NacosConfigurator struct {
	client *config_client.IConfigClient
	dataId string
	group  string
}

func NewNacosConfigurator(serverAddr, dataId, group, namespace string) (*NacosConfigurator, error) {
	sc := []constant.ServerConfig{{IpAddr: serverAddr, Port: 8848}}
	cc := constant.ClientConfig{NamespaceId: namespace, TimeoutMs: 5000}
	client, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)
	return &NacosConfigurator{
		client: &client,
		dataId: dataId,
		group:  group,
	}, err
}

// GetConfig 实现配置加载
func (n *NacosConfigurator) GetConfig() (string, error) {
	content, err := (*n.client).GetConfig(vo.ConfigParam{
		DataId: n.dataId,
		Group:  n.group,
	})
	return content, err
}

// AddListener 实现配置变更监听
func (n *NacosConfigurator) AddListener(listener func()) {
	err := (*n.client).ListenConfig(vo.ConfigParam{
		DataId: n.dataId,
		Group:  n.group,
		OnChange: func(namespace, group, dataId, data string) {
			listener()
		},
	})
	if err != nil {
		panic(err)
	}
}
